/**
 * 
 */
package com.yonder.agenda.service.generic;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.IteratorUtils;

import com.yonder.agenda.entity.generic.AbstractEntity;
import com.yonder.agenda.repository.generic.EntityRepository;

/**
 * Abstract class for model service .
 * 
 * @author CosminS
 * @since Jan 29, 2014
 * @param <T>
 *            Entity type
 */
public abstract class AbstractEntityService<T extends AbstractEntity> implements EntityService<T> {

	/**
	 * Entity repository.
	 * 
	 * @return Repository instance
	 */
	protected abstract EntityRepository<T> getRepository();

	@Override
	public T create(T entity) {
		return getRepository().save(entity);
	}

	@Override
	public T update(T entity) {
		return getRepository().save(entity);
	}

	@Override
	public void remove(Long entityId) {
		getRepository().delete(entityId);
	}

	@Override
	public T findById(Long entityId) {
		return getRepository().findById(entityId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll() {
		Iterable<T> iterable = getRepository().findAll();

		if (iterable == null) {
			return new ArrayList<>();
		}
		return IteratorUtils.toList(iterable.iterator());
	}
}